package com.cn.yugan.Activity;

import android.app.backup.FullBackupDataOutput;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.yugan.Engine.Http.AddReqCookie;
import com.cn.yugan.Utils.Dialog.CustomDialog;
import com.cn.yugan.Utils.ImgUtils;
import com.cn.yugan.Utils.LogUtils;
import com.cn.yugan.Utils.StringConv;
import com.cn.yugan.Utils.ToastUtils;
import com.cn.yugan.Widget.CircularImage.CircularImage;
import com.cn.yugan.mobile.R;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Rover on 2016/7/21 .
 * Email 357319517@qq.com
 * 个人信息页面(可编写)
 */

public class UserinfoActivity extends AppCompatActivity implements View.OnClickListener {

    private RelativeLayout mrluserimg;
    private RelativeLayout mrlusersign;
    private RelativeLayout mrlusername;
    private RelativeLayout mrlusersex;
    private RelativeLayout mrluseremail;
    private RelativeLayout mrluserphone;
    private Button mbtsingout;
    private Drawable userimg;
    private String username = "";
    private String sex = "";
    private String email = "";
    private String phone = "";

    private CircularImage userinfo_userimg;
    private TextView userinfo_username;
    private TextView userinfo_uid;
    private TextView userinfo_regtime;
    private TextView userinfo_member;
    private TextView userinfo_name;
    private TextView userinfo_sex;
    private TextView userinfo_email;
    private TextView userinfo_phone;

    private String sign;
    private SharedPreferences sp;
    //上传图片本地uri
    private String photoPath;
    private String key = "";
    private String token = "";
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                key = msg.obj.toString();
                LogUtils.d(key);
            }
            if (msg.what == 1) {
                token = msg.obj.toString();
                LogUtils.d(token);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);
        Intent intent = getIntent();
        sp = getSharedPreferences("Session", MODE_PRIVATE);
        byte[] bytes = intent.getByteArrayExtra("userimg");
        userimg = ImgUtils.Bytes2Drawable(bytes);
        init();
    }

    private void init() {
        //设置actionbar
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("修改个人信息");
        actionBar.setDisplayHomeAsUpEnabled(true);

        sign = sp.getString("intro", "请编辑您的个性签名");

        mrluserimg = (RelativeLayout) findViewById(R.id.userinfo_rl_img);
        mrlusersign = (RelativeLayout) findViewById(R.id.userinfo_rl_sign);
//        mrlusername = (RelativeLayout) findViewById(R.id.userinfo_rl_name);
//        mrlusersex = (RelativeLayout) findViewById(R.id.userinfo_rl_sex);
//        mrluseremail = (RelativeLayout) findViewById(R.id.userinfo_rl_email);
        mrluserphone = (RelativeLayout) findViewById(R.id.userinfo_rl_phone);
        mbtsingout = (Button) findViewById(R.id.userinfo_bt_signout);

        userinfo_userimg = (CircularImage) findViewById(R.id.userinfo_userimg);
        userinfo_username = (TextView) findViewById(R.id.userinfo_username);
        userinfo_uid = (TextView) findViewById(R.id.userinfo_uid);
        userinfo_regtime = (TextView) findViewById(R.id.userinfo_regtime);
//        userinfo_member = (TextView) findViewById(R.id.userinfo_member);
//        userinfo_name = (TextView) findViewById(R.id.userinfo_name);
//        userinfo_sex = (TextView) findViewById(R.id.userinfo_sex);
//        userinfo_email = (TextView) findViewById(R.id.userinfo_email);
        userinfo_phone = (TextView) findViewById(R.id.userinfo_phone);

        userinfo_userimg.setImageDrawable(userimg);
        userinfo_username.setText(StringConv.sp2normal(sp.getString("name", "")));
        userinfo_uid.setText(StringConv.sp2normal(sp.getString("uid", "")));
        LogUtils.d(sp.getString("regtime", ""));
        userinfo_regtime.setText(sp.getString("regtime", ""));
//        userinfo_member.setText(StringConv.sp2normal(sp.getString("lv", null)));
//        userinfo_name.setText(StringConv.sp2normal(sp.getString("name", null)));
//        userinfo_sex.setText(StringConv.sp2normal(sp.getString("sex", null)));
//        userinfo_email.setText(StringConv.sp2normal(sp.getString("email", null)));
        userinfo_phone.setText(sp.getString("phone", ""));

        mrluserimg.setOnClickListener(this);
        mrlusersign.setOnClickListener(this);
//        mrlusername.setOnClickListener(this);
//        mrlusersex.setOnClickListener(this);
        mbtsingout.setOnClickListener(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        MenuInflater inflater = getMenuInflater();
//        inflater.inflate(R.menu.action_userinfo_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
//            case R.id.action_save:
//                //个人信息存储逻辑
//                Toast.makeText(this, "功能暂未开放", Toast.LENGTH_SHORT).show();
//                break;
            case android.R.id.home:
                this.finish();
                break;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        final CustomDialog.Builder builder = new CustomDialog.Builder(this);
        switch (v.getId()) {
            case R.id.userinfo_rl_img:
                //使用Intent触发选择Action
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                //打开系统提供的图片选择界面
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                //传参以在返回本界面时触发加载图片的功能
                startActivityForResult(intent, 0x1);
                break;
            case R.id.userinfo_rl_sign:
                builder.setEditHint(sign);
                builder.setTitle("编写您的个性签名");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //设置你的操作事项
                        final String intro = builder.getEditText().getText().toString().trim();
                        AsyncHttpClient asyncHttpClient = new AsyncHttpClient(true, 80, 443);
                        asyncHttpClient.addHeader("cookie",AddReqCookie.getNormalheader(UserinfoActivity.this));
                        RequestParams params = new RequestParams();
                        params.put("type", "intro");
                        params.put("value", intro);
                        asyncHttpClient.post(getString(R.string.serverurl) + getString(R.string.setinfo), params, new AsyncHttpResponseHandler() {
                            @Override
                            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                                try {
                                    JSONObject jsonObject = new JSONObject(new String(bytes, "utf-8"));
                                    if (jsonObject.getBoolean("success")) {
                                        ToastUtils.show(UserinfoActivity.this, "修改成功!");
                                        sign = intro;
                                    } else {
                                        ToastUtils.show(UserinfoActivity.this, "修改失败!");
                                        LogUtils.d(jsonObject.toString());
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                            }
                        });
                    }
                });

                builder.setNegativeButton("取消",
                        new android.content.DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                builder.create().show();
                break;
//            case R.id.userinfo_rl_name:
//                builder.setEditHint(username);
//                builder.setTitle("编写您的姓名");
//                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        //设置你的操作事项
//                    }
//                });
//
//                builder.setNegativeButton("取消",
//                        new android.content.DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                            }
//                        });
//
//                builder.create().show();
//                break;
//            case R.id.userinfo_rl_sex:
//                builder.setRadioGroup(sex);
//                builder.setTitle("请编辑您的性别");
//                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        //设置你的操作事项
//                    }
//                });
//
//                builder.setNegativeButton("取消",
//                        new android.content.DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                            }
//                        });
//
//                builder.create().show();
//                break;
//            case R.id.userinfo_rl_email:
//                builder.setEditHint(email);
//                builder.setTitle("编写您的邮箱");
//                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        //设置你的操作事项
//                    }
//                });
//
//                builder.setNegativeButton("取消",
//                        new android.content.DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                            }
//                        });
//
//                builder.create().show();
//                break;
//            case R.id.userinfo_rl_phone:
//                builder.setEditHint(phone);
//                builder.setTitle("编写您的姓名");
//                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        //设置你的操作事项
//                    }
//                });
//
//                builder.setNegativeButton("取消",
//                        new android.content.DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                            }
//                        });
//
//                builder.create().show();
//                break;
            case R.id.userinfo_bt_signout:
                builder.setMessage("确定要退出登录？");
                builder.setTitle("提示");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //设置你的操作事项
                        IndexActivity.instance.finish();
                        UserinfoActivity.this.finish();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.clear();
                        editor.commit();
                        Intent intent = new Intent(UserinfoActivity.this, LoginAcitivity.class);
                        startActivity(intent);
                    }
                });

                builder.setNegativeButton("取消",
                        new android.content.DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                break;
        }
    }

    //图片选择后回调次方法
    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        //获取token和key
        final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(true, 80, 443);
        asyncHttpClient.addHeader("cookie", AddReqCookie.getNormalheader(this));
        RequestParams params = new RequestParams();
        params.put("type", "userface");
        asyncHttpClient.post(getString(R.string.serverurl) + getString(R.string.token), params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes, "utf-8"));
                    LogUtils.d(jsonObject.toString());
                    Message msg0 = Message.obtain();
                    msg0.what = 0;
                    msg0.obj = jsonObject.getJSONObject("data").getString("key");
                    handler.sendMessage(msg0);

                    Message msg1 = Message.obtain();
                    msg1.what = 1;
                    msg1.obj = jsonObject.getJSONObject("data").getString("token");
                    handler.sendMessage(msg1);
                } catch (JSONException e) {
                } catch (UnsupportedEncodingException e) {
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                ToastUtils.show(UserinfoActivity.this, "token获取失败");
            }
        });
        //上传头像
        if (requestCode == 0x1 && resultCode == RESULT_OK) {
            if (data != null) {
                ContentResolver resolver = getContentResolver();
                try {
                    // 获取圖片URI
                    Uri uri = data.getData();
                    // 将URI转换为路径：
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = managedQuery(uri, proj, null, null, null);
                    // 这个是获得用户选择的图片的索引值
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    // 最后根据索引值获取图片路径
                    photoPath = cursor.getString(column_index);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            final File file = new File(photoPath);
                            LogUtils.d(file.getName() + " " + file.getPath());
                            //循环等待token
                            while (true) {
                                if (!"".equals(token)) {
                                    //domain: '//ohx8mf27p.qnssl.com/',
                                    UploadManager uploadManager = new UploadManager();
                                    uploadManager.put(file, key, token,
                                            new UpCompletionHandler() {
                                                @Override
                                                public void complete(String key, ResponseInfo info, JSONObject res) {
                                                    //res包含hash、key等信息，具体字段取决于上传策略的设置
                                                    LogUtils.d(key);
                                                    LogUtils.d(info + "");
                                                    LogUtils.d(res + "");
                                                    if (info.isOK()) {
                                                        RequestParams requestParams = new RequestParams();
                                                        //通知前端服务器最新头像.
                                                        requestParams.put("type", "img");
                                                        requestParams.put("value", key + "?ts=" + System.currentTimeMillis());
                                                        LogUtils.d(key + "?ts=" + System.currentTimeMillis());
                                                        asyncHttpClient.post(getString(R.string.serverurl) + getString(R.string.setinfo), requestParams, new AsyncHttpResponseHandler() {
                                                            @Override
                                                            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                                                                try {
                                                                    LogUtils.d(new String(bytes, "UTF-8"));
                                                                } catch (UnsupportedEncodingException e) {
                                                                    e.printStackTrace();
                                                                }
                                                                ToastUtils.show(UserinfoActivity.this, "上传成功！");
                                                                userinfo_userimg.setImageDrawable(Drawable.createFromPath(photoPath));
                                                            }

                                                            @Override
                                                            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                                                                ToastUtils.show(UserinfoActivity.this, "上传失败！");
                                                            }
                                                        });
                                                    } else {
                                                        LogUtils.d(info.error);
                                                    }
                                                }
                                            }, new UploadOptions(null, null, false,                 //回调进度显示
                                                    new UpProgressHandler() {
                                                        @Override
                                                        public void progress(String key, double percent) {
                                                            LogUtils.d("process" + percent);
                                                        }
                                                    }, null));
                                    break;
                                } else {
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                    }
                                }
                            }
                        }
                    }).start();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
